<template>
<div> 
  <div style="margin:0 auto 0.8rem auto;display:flex;justify-content: space-between;">
    <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
    <el-dialog title="添加用户"  :visible.sync="dialogVisible" width="50%"
      :closeOnClickModal='false'
       :closeOnPressEscape="false">
      <el-form ref="form" :model="form" status-icon  label-width="80px" :rules="rules" >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="form.age" placeholder="请填入纯数字"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="tel">
          <el-input v-model="form.tel"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input type="textarea" v-model="form.address"></el-input>
        </el-form-item>
      </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="saveUserInfo('form')">添加</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </span>
    </el-dialog>
    <el-dialog title="更新用户信息"  :visible.sync="dialogVisible2" width="50%"
      :closeOnClickModal='false'
       :closeOnPressEscape="false">
      <el-form ref="form" :model="form"  status-icon  label-width="80px" :rules="rules">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="form.age" placeholder="请填入纯数字"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="tel">
          <el-input v-model="form.tel"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input type="textarea" v-model="form.address"></el-input>
        </el-form-item>
      </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="updateUserInfo('form')">提交</el-button>
          <el-button @click="dialogVisible2 = false">取消</el-button>
        </span>
    </el-dialog>
    <el-select v-model="size" placeholder="请选择展示尺寸" @change="getSize">
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
  </div>
  <el-table :data="tableData" style="width: 100%" border 
  :row-class-name="tableRowClassName"
  v-loading="isLoading"
  >
    <el-table-column prop="id" align="center" label="序列号" width="120"></el-table-column>
    <el-table-column prop="name" align="center" label="姓名" width="160">
       <template slot-scope="scope">
        <el-popover trigger="hover" placement="top">
          <p>姓名: {{ scope.row.name }}</p>
          <p>住址: {{ scope.row.address }}</p>
          <div slot="reference" class="name-wrapper">
            <el-tag size="medium">{{ scope.row.name }}</el-tag>
          </div>
        </el-popover>
      </template>
    </el-table-column>
    <el-table-column prop="sex " align="center" :formatter="fmtSex" label="性别" width="160"></el-table-column>
    <el-table-column prop="age" align="center" label="年龄" width="160"></el-table-column>
    <el-table-column prop="tel" align="center" label="电话" width="180"></el-table-column>
    <el-table-column prop="address" align="center" label="地址"></el-table-column>
    <el-table-column label="操作" align="center">
      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="handleEdit(scope.row)">编辑</el-button>
        <el-button
          size="mini"
          type="danger"
          @click="delHandle(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <div style="text-align:center;margin:10px 0;">
    <el-pagination
      background
      :current-page.sync="pageIndex"
      :page-size="pageSize"
      layout="prev, pager, next" 
      @current-change="getUserList"
      :total="userCount">
    </el-pagination>
  </div>
</div>
</template>

<script>
export default {
  name:'UserList',
  data() {
    var addressCheck=(rule, value, callback)=>{
      if(!value){
        return callback(new Error('地址不能为空'))
      }else{
        return callback();
      }
     }
    var telCheck=(rule, value, callback)=>{
      if(!value){
        return callback(new Error('电话号不能为空'))
      }else if(!(/^1[3456789]\d{9}$/.test(value))){
        return callback(new Error('电话号格式有误'))
      }else{
        return callback();
      }
     }
    var sexCheck=(rule, value, callback)=>{
      if(value!=="男"&&value!=="女"){
        return callback(new Error('请输入性别'))
      }else{
         return callback();
      }
     }
    var nameCheck=(rule, value, callback)=>{
      if(!value){
        return callback(new Error('姓名不能为空'))
      }else if(/^[0-9_-]+$/.test(value)){
        return callback(new Error('用户名格式不规范'))
      }else{
        this.$http.post('/validname',{name:value}).then(res=>{
          if(res.data.code==1){
            return callback(new Error('用户已占用'));
          }else if(/^[0-9_-]+$/.test(value)){
            return callback(new Error('用户名格式不规范'))
          }else{
            return callback()
          }
        })
      }
      }
    var ageCheck =( rule, value, callback)=>{
        if(!value){
          return callback(new Error('年龄不能为空'))
        }else if (!(/^\d+$/.test(value))) {
          callback (new Error('请输入数字值'));
        } else if (value < 18) {
            callback (new Error('必须年满18岁'));
        } else if(value > 100) {
            callback (new Error('都100了,还玩这个吗'));
        } else {
            callback ();
        }
     }
    return {
      rules:{
        name:[
          {validator: nameCheck, trigger: 'blur'}
        ],
        age:[
          {validator: ageCheck, trigger: 'blur'}
        ],
        sex:[
          {validator: sexCheck, trigger: 'blur'}
        ],
        tel:[
          {validator: telCheck, trigger: 'blur'}
        ],
        address:[
          {validator: addressCheck, trigger: 'blur'}
        ]
      },
      form: {
        name: '',
        age: '',
        sex: '',
        tel: '',
        address: ''
      },
      idIndex:0,
      dialogVisible:false,
      dialogVisible2:false,
      tableData: [],
      isLoading:false,
      pageSize:5,
      userCount:0,
      size:'',
      pageIndex:1,
      options:[{
          value: '4',
          label: '4'
        }, {
          value: '5',
          label: '5'
        }, {
          value: '6',
          label: '6'
        }, {
          value: '7',
          label: '7'
        }, {
          value: '8',
          label: '8'
        }]
    }
  },
  methods: {
    saveUserInfo(form){
      this.$refs[form].validate(valid => {
          if (valid) {
            this.$http.post(`/adduser`,this.form).then(res=>{
              this.dialogVisible=false;
              if(res.data.code==1){
                this.getUserList();
                this.$success('添加成功');
                this.form.name="";
                this.form.age="";
                this.form.sex="";
                this.form.tel="";
                this.form.address="";
              }else{
                 this.$fail('添加失败');
                 return false;
              }
            })
          } else {
            this.$fail('添加失败');
            return false;
          }
        });
    },
    updateUserInfo(form){
    this.$refs[form].validate(valid => {
          if (valid) {
            this.$http.post(`/updata`,{form:this.form,id:this.idIndex}).then(res=>{
              this.dialogVisible2=false;
              if(res.data.code){
                this.$success('更新成功');
                this.getUserList();
                this.form.name="";
                this.form.age="";
                this.form.sex="";
                this.form.tel="";
                this.form.address="";
              }else{
                 this.$fail('更新失败');
                 return false;
              }
            })
            } else {
            this.$fail('更新失败');
            return false;
          }
        });
    },
    getSize(index){
      let num=(this.pageIndex-1)*this.pageSize+1;
      this.pageSize=Number(index);
      console.log(num)
      this.pageIndex=Math.ceil(num/this.pageSize);
      console.log(this.pageIndex)
      console.log(this.pageSize)
      this.getUserList();
    },
    tableRowClassName({rowIndex}) {
        if (rowIndex%3 === 1) {
          return 'warning-row';
        } else if (rowIndex%3 === 0) {
          return 'success-row';
        }
        return '';
      },
    fmtSex(row){
      // return row.sex==1?'男':'女';
      return ['女','男'][row.sex] || '未知'
    },
    handleEdit(row){
      this.idIndex=row.id
      this.dialogVisible2=true;
      this.form.name=row.name;
      this.form.sex=(row.sex==1?'男':'女');
      this.form.age=row.age
      this.form.tel=row.tel;
      this.form.address=row.address;
    },
    delHandle(row){
      this.$confirm(`确定删除${row.id}?`, '系统提示', {
          confirmButtonText: 'YES',
          cancelButtonText: 'NO',
          type: 'warning'
        }).then(() => {
          this.$http.post(`/remove`,{id:row.id}).then(res=>{
            if(res.data.code==1){
              this.userCount--;
              if(this.tableData.length==1){
                this.pageIndex--;
              }
              this.getUserList();
              this.$success('删除成功!');
            }else{
              this.$fail('删除失败!');
            }
          })
          
        })
    },
    getUserCount(){
      this.$http.get('/count',{
      }).then((res)=>{
        this.userCount=res.data;
      })
    },
    getUserList(){
      this.getUserCount();
      this.isLoading=true;
      console.log('---'+this.pageIndex)
      console.log('---'+this.pageSize)
      this.$http.post('/user',{
        params:{
          pageIndex:this.pageIndex,
          pageSize:this.pageSize
        }
      }).then((res)=>{
        this.tableData=res.data;
        this.isLoading=false;
      })
    }
  },
  created(){
    this.getUserList();
  },
}
</script>

<style>
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
  .el-dialog__headerbtn {
    display: none;
  }
</style>